package com.cyz.common.service.impl;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.cyz.common.enums.MyEnums;
import com.cyz.common.exception.MyException;
import com.cyz.common.service.UploadService;
import com.cyz.common.utils.PathUtils;
import com.cyz.common.utils.R;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Arrays;
import java.util.List;

@Service
@Data
//匹配配置文件赋值
@ConfigurationProperties(prefix = "oss")
public class UploadServiceImpl implements UploadService {

    public static final List<String> FILE_TYPE_WHITE = Arrays.asList(".png",".jpg");

    private String accessKey;
    private String secretKey;
    private String bucket;
    private String httpPath;

    @Override
    public R uploadImg(MultipartFile img) {
        //获取文件后缀是否符合规定
        String originalFilename = img.getOriginalFilename();
        if(!FILE_TYPE_WHITE.contains(originalFilename.substring(originalFilename.indexOf(".")))){
            throw new MyException(MyEnums.FILE_TYPE_ERROR);
        }
        //生成保存路径
        String filePath = PathUtils.generateFilePath(originalFilename);
        //官方存取方法
        String url = uploadOss(img,filePath);
        //返回访问路径
        return R.success(url);
    }

    private String uploadOss(MultipartFile img,String filePath){
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.autoRegion());
        //cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;
        // 指定分片上传版本
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传
        //String accessKey = "your access key";
        //String secretKey = "your secret key";
        //String bucket = "your bucket name";
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = filePath;
        try {
            InputStream inputStream = img.getInputStream();
//            byte[] uploadBytes = "hello qiniu cloud".getBytes("utf-8");
//            ByteArrayInputStream byteInputStream=new ByteArrayInputStream(uploadBytes);
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);
            try {
                Response response = uploadManager.put(inputStream,key,upToken,null, null);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                return httpPath+key;
            } catch (QiniuException ex) {
                throw new MyException(MyEnums.FILE_UPLOAD_FAIL);
            }
        } catch (Exception ex) {
            throw new MyException(MyEnums.FILE_UPLOAD_FAIL);
        }
    }
}
